package com.loveprogrammer.handler;

import com.loveprogrammer.network.NetworkClientListener;
import com.loveprogrammer.pojo.StringMessage;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TcpMessageStringHandler extends SimpleChannelInboundHandler<StringMessage> {

    protected static final Logger logger = LoggerFactory.getLogger(NetworkClientListener.class);

    private final NetworkClientListener networkListener;

    public TcpMessageStringHandler(NetworkClientListener networkListener) {
        this.networkListener = networkListener;
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext arg0, Throwable arg1) {
        logger.info("异常发生", arg1);
    }

    @Override
    public void channelRead(ChannelHandlerContext arg0, Object msg) throws Exception {
        super.channelRead(arg0, msg);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, StringMessage data) {
        // logger.info("数据内容：data=" + data);

        // 消息分发 对于消息的处理要增加多线程
        networkListener.channelRead(ctx,data);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        logger.info("客户端连接建立");
        super.channelActive(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        logger.info("客户端连接断开");
        super.channelInactive(ctx);
    }
}
